<?php
session_start();
// 检查是否登录
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php?redirect=create.php');
    exit;
}

include 'config.php';

$success = false;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 验证表单数据
    if (empty($_POST['title']) || empty($_POST['content']) || empty($_POST['category'])) {
        $error = '标题、内容和分类不能为空';
    } else {
        // 获取表单数据
        $title = $_POST['title'];
        $markdownContent = $_POST['content'];
        $category = $_POST['category'];
        $tags = !empty($_POST['tags']) ? $_POST['tags'] : '';

        // 解析Markdown为HTML 2.0版本不可用
        //$htmlContent = Markdown::defaultTransform($markdownContent);
        //2.0以后版本使用下面代码
        //$parser = new Markdown();
        //$htmlContent = $parser->transform($markdownContent);
        //适配不同版本代码
        //if (method_exists(Markdown::class, 'defaultTransform')) {
        //    $htmlContent = Markdown::defaultTransform($markdownContent); // 旧版静态调用
        //} else {
        //    $parser = new Markdown();
        //    $htmlContent = $parser->transform($markdownContent); // 新版实例调用
        //}
        $parsedown = new Parsedown();
        $htmlContent = $parsedown->text($markdownContent);



        // 插入数据库
        try {
            $stmt = $pdo->prepare("INSERT INTO aiwz_articles (title, content, markdown_content, category, tags) 
                                  VALUES (:title, :content, :markdown_content, :category, :tags)");
            $stmt->bindParam(':title', $title);
            $stmt->bindParam(':content', $htmlContent);
            $stmt->bindParam(':markdown_content', $markdownContent);
            $stmt->bindParam(':category', $category);
            $stmt->bindParam(':tags', $tags);
            $stmt->execute();

            $success = true;
        } catch (PDOException $e) {
            $error = '发布失败: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布文章 - Markdown博客</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github-dark.min.css">
    <style>
        .editor-container {
            border: 1px solid #ddd;
            border-radius: 5px;
            overflow: hidden;
        }

        .editor-tabs {
            display: flex;
            background-color: #f8f9fa;
            border-bottom: 1px solid #ddd;
        }

        .editor-tab {
            padding: 10px 15px;
            cursor: pointer;
            border: none;
            background: none;
            flex: 1;
            text-align: center;
        }

        .editor-tab.active {
            background-color: white;
            border-bottom: 3px solid #0d6efd;
        }

        .editor-content {
            min-height: 400px!important;
        }

        #preview {
            padding: 15px;
            background-color: white;
        }

        #preview img {
            max-width: 100%;
            height: auto;
        }

        #preview pre {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            overflow-x: auto;
        }

        .toolbar {
            padding: 10px;
            border-bottom: 1px solid #ddd;
            background-color: #f8f9fa;
        }

        .toolbar button {
            margin-right: 5px;
            padding: 5px 10px;
            border: 1px solid #ddd;
            background-color: white;
            border-radius: 3px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-4">
        <div class="container">
            <a class="navbar-brand" href="index.php">Markdown博客</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="create.php">发布文章</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="settings.php">设置</a>
                    </li>
                </ul>
                <div class="dropdown">
                    <button class="btn btn-outline-light dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <?php echo htmlspecialchars($_SESSION['username']); ?>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="logout.php">退出登录</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="row">
            <div class="col-md-10 offset-md-1">
                <h1 class="mb-4">发布文章</h1>

                <?php if ($success): ?>
                    <div class="alert alert-success">
                        文章发布成功！<a href="index.php">返回首页</a> 或 <a href="create.php">继续发布</a>
                    </div>
                <?php endif; ?>

                <?php if (!empty($error)): ?>
                    <div class="alert alert-danger">
                        <?php echo $error; ?>
                    </div>
                <?php endif; ?>

                <form method="post">
                    <div class="mb-3">
                        <label for="title" class="form-label">文章标题</label>
                        <input type="text" class="form-control" id="title" name="title" required>
                    </div>

                    <div class="mb-3">
                        <label for="category" class="form-label">分类</label>
                        <select class="form-select" id="category" name="category" required>
                            <option value="">选择分类</option>
                            <option value="技术">技术</option>
                            <option value="生活">生活</option>
                            <option value="旅行">旅行</option>
                            <option value="美食">美食</option>
                            <option value="其他">其他</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="tags" class="form-label">标签（用逗号分隔）</label>
                        <input type="text" class="form-control" id="tags" name="tags" placeholder="例如：php,markdown,编程">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">文章内容（支持Markdown）</label>
                        <div class="editor-container">
                            <div class="toolbar">
                                <button type="button" data-command="heading" data-value="1"># 标题</button>
                                <button type="button" data-command="heading" data-value="2">## 标题</button>
                                <button type="button" data-command="bold"><b>粗体</b></button>
                                <button type="button" data-command="italic"><i>斜体</i></button>
                                <button type="button" data-command="link">链接</button>
                                <button type="button" data-command="image">图片</button>
                                <button type="button" data-command="list" data-value="ul">列表</button>
                                <button type="button" data-command="list" data-value="ol">有序列表</button>
                                <button type="button" data-command="code">代码</button>
                                <button type="button" data-command="quote">引用</button>
                            </div>
                            <div class="editor-tabs">
                                <button class="editor-tab active" data-mode="edit">编辑</button>
                                <button class="editor-tab" data-mode="preview">预览</button>
                            </div>
                            <textarea class="form-control editor-content" id="content" name="content"
                                required></textarea>
                            <div id="preview" class="editor-content d-none"></div>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary">发布文章</button>
                    <a href="index.php" class="btn btn-outline-secondary ms-2">取消</a>
                </form>
            </div>
        </div>
    </div>

    <footer class="bg-dark text-white mt-5 py-4">
        <div class="container text-center">
            <p>&copy; <?php echo date('Y'); ?> Markdown博客 - 用技术记录生活</p>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
    <script>
        // Markdown编辑器功能
        document.addEventListener('DOMContentLoaded', function () {
            const editTab = document.querySelector('.editor-tab[data-mode="edit"]');
            const previewTab = document.querySelector('.editor-tab[data-mode="preview"]');
            const editContent = document.getElementById('content');
            const previewContent = document.getElementById('preview');
            const toolbarButtons = document.querySelectorAll('.toolbar button');

            // 切换编辑和预览模式
            editTab.addEventListener('click', function () {
                editTab.classList.add('active');
                previewTab.classList.remove('active');
                editContent.classList.remove('d-none');
                previewContent.classList.add('d-none');
            });

            previewTab.addEventListener('click', function () {
                editTab.classList.remove('active');
                previewTab.classList.add('active');
                editContent.classList.add('d-none');
                previewContent.classList.remove('d-none');

                // 转换Markdown为HTML并显示
                fetch('preview.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'content=' + encodeURIComponent(editContent.value)
                })
                    .then(response => response.text())
                    .then(html => {
                        previewContent.innerHTML = html;
                        hljs.highlightAll();
                    });
            });

            // 工具栏按钮功能
            toolbarButtons.forEach(button => {
                button.addEventListener('click', function () {
                    const command = this.getAttribute('data-command');
                    const value = this.getAttribute('data-value');

                    // 获取光标位置和选中的文本
                    const start = editContent.selectionStart;
                    const end = editContent.selectionEnd;
                    const selectedText = editContent.value.substring(start, end);

                    let insertText = '';

                    switch (command) {
                        case 'heading':
                            insertText = '#'.repeat(value) + ' ' + (selectedText || '标题');
                            break;
                        case 'bold':
                            insertText = '**' + (selectedText || '粗体文本') + '**';
                            break;
                        case 'italic':
                            insertText = '*' + (selectedText || '斜体文本') + '*';
                            break;
                        case 'link':
                            insertText = '[' + (selectedText || '链接文本') + '](https://example.com)';
                            break;
                        case 'image':
                            insertText = '![图片描述](' + (selectedText || 'https://example.com/image.jpg') + ')';
                            break;
                        case 'list':
                            if (value === 'ul') {
                                insertText = '- ' + (selectedText || '列表项');
                            } else {
                                insertText = '1. ' + (selectedText || '列表项');
                            }
                            break;
                        case 'code':
                            if (selectedText.includes('\n')) {
                                insertText = '```\n' + selectedText + '\n```';
                            } else {
                                insertText = '`' + (selectedText || '代码') + '`';
                            }
                            break;
                        case 'quote':
                            insertText = '> ' + (selectedText || '引用文本');
                            break;
                    }

                    // 插入文本并调整光标位置
                    editContent.value = editContent.value.substring(0, start) +
                        insertText +
                        editContent.value.substring(end);

                    // 移动光标到插入文本的末尾
                    const newCursorPos = start + insertText.length;
                    editContent.focus();
                    editContent.setSelectionRange(newCursorPos, newCursorPos);
                });
            });
        });
    </script>
</body>

</html>